/*
 * @Author: chengjiang
 * @Date: 2024-10-31 10:23:26
 * @Description: 
 */
import {
  createRouter,
  createWebHashHistory,
  RouteRecordRaw
} from 'vue-router'
import Home from '../views/home.vue'
import Vuex from '../views/vuex.vue'
import Login from '../views/Login.vue'
import { getToken } from '../utils/token'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/account',
        name: 'Account',
        component: () => import('../views/child/AccountPage.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/gold/:priceType',
        name: 'Gold',
        component: () => import('../views/child/GoldPage.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/customer',
        name: 'Customer',
        component: () => import('../views/child/GoldPage.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/preview',
        name: 'Preview',
        component: () => import('../views/child/PreView.vue'),
        meta: { requiresAuth: true }
      },
    ],
    meta: { requiresAuth: true }
  },
  {
    path: '/vuex',
    name: 'Vuex',
    component: Vuex,
    meta: { requiresAuth: true }
  },
  {
    path: '/axios',
    name: 'Axios',
    meta: { role: 'B' },
    component: () => import('../views/AxiosPage.vue'), // 懒加载组件
  },
  {
    path: '/login',
    name: 'Login',
    meta: { role: 'B' },
    component: Login // 懒加载组件
  },
  {
    path: '/:pathMatch(.*)',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, _, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  console.log('路由监听')
  if (requiresAuth && !isAuthenticated()) {
    next({ name: 'Login' });
  } else {
    if (to.path === '/') {
      next({path: '/gold/1'})
    }
    next();
  }
})

function isAuthenticated() {
  // 检查用户是否已登录，这里只是一个示例
  // 你可以根据实际情况从 localStorage、Vuex 等地方获取登录状态
  console.log('isAuthenticated', getToken())
  return getToken() !== null;
}

export default router